package com.jtjrenren.android.taxi.driver.utils;

import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jtjrenren.android.taxi.driver.Constants;
import com.jtjrenren.android.taxi.driver.R;
import com.jtjrenren.android.taxi.driver.bean.api.ApiCommonT;
import com.jtjrenren.android.taxi.driver.core.splash.SplashInteractorImpl;
import com.jtjrenren.android.taxi.driver.manger.AppManger;
import com.jtjrenren.android.taxi.driver.manger.push.cmd.Protocl;
import com.library.utils.Base64;
import com.library.utils.CipherUtils;
import com.library.utils.DensityUtils;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import datetime.DateTime;

/**
 * Created by Administrator on 2016/2/26.
 */
public class ModuleUtils {
    public static boolean handCommon(int code) {
        if (code == 1)
            return true;
        else if (code == 11) {
            //tokent失效，需要重新获取
            AppManger.getInstance().getToken(true);
        }else if (code==21){
            //clientID么有
            AppManger.getInstance().bindGtID(AppManger.getInstance().gtCID);
        }
        return false;
    }

    //
    public static <T> ApiCommonT getCommonApi(String json, Class<T> clazz) {
        ApiCommonT<T> apiCommonT = null;
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
            apiCommonT = new ApiCommonT<>();
            int code = jsonObject.getInt("code");
            String msg = jsonObject.getString("msg");
            String data = jsonObject.getString("data");
            if (!StringUtils.isEmpty(data)) {
                List list = GsonUtils.fromJsonArray(data, clazz);
                apiCommonT.setData(list);
            }
            apiCommonT.setCode(code);
            apiCommonT.setMsg(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonObject = null;
        return apiCommonT;
    }

    //将从网络获取逇订单的状态转换为本地订单的状态
    public static int orderStatusAdapter(int status) {
        int localstatus = Constants.STATUS_ORDER_CREATE;
        if (status == 10) {
            localstatus = Constants.STATUS_ORDER_CREATE;
        } else if (status == 9) {
            localstatus = Constants.STATUS_ORDER_QJCK;
        } else if (status == 2) {
            localstatus = Constants.STATUS_ORDER_CKSC;
        } else if (status == 3 || status == 7 || status == 11) {
            localstatus = Constants.STATUS_ORDER_FINISH;
        } else if (status == 8 || status == 12 || status == 4 || status == 5 || status == 6) {
            localstatus = Constants.STATUS_ORDER_CANCLE;
        }
        return localstatus;
    }

    //将从网络获取逇订单的支付状态转换为本地订单的支付状态
    public static int orderPayStatusAdapter(String payStatus) {
        int localPayStatus = Constants.STATUS_ORDER_PAY_NOTCOMMIT;
        if (!StringUtils.isEmpty(payStatus)) {
            if ("0".equals(payStatus))
                localPayStatus = Constants.STATUS_ORDER_PAY_NO;
            else
                localPayStatus = Constants.STATUS_ORDER_PAY_YES;
        }
        return localPayStatus;
    }


    public static String getStringByResource(Context context, int id) {
        return context.getResources().getString(id);
    }


    public static String getUniquePsuedoID(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String DEVICE_ID = tm.getDeviceId();
        return DEVICE_ID;
    }

    /**
     * 获取提交费用的时间显示  hhmm
     *
     * @param time
     * @return
     */
    public static String getTjFyTime(double time) {
        int hour = (int) (time / 60);
        int min = (int) (time % 60);

        String hourStr = String.valueOf(hour);
        if (hourStr.length() == 1)
            hourStr = "0" + hourStr;
        String minStr = String.valueOf(min);
        if (minStr.length() == 1)
            minStr = "0" + minStr;

        return hourStr + minStr;
    }


    public static String[] parseXdDesc(String addrDesc) {
        String[] desc = new String[]{"", "", "", ""};
        //乘客距离您2469米，乘车点：宝安区华辉路博恩，目的地：深圳市宝安区深圳龙华汽车站,小费4元
        if (!StringUtils.isEmpty(addrDesc)) {
            addrDesc = addrDesc.replaceAll("乘车点：", "").replaceAll("目的地：", "");
            String[] split = addrDesc.split("，");
            for (int i = 0; i < split.length; i++) {
                desc[i] = split[i];
            }
        }
        return desc;
    }

    /**
     * 获取费用显示的列表
     *
     * @param activity
     * @param str
     * @return
     */
    public static List<LinearLayout> showEstimatedCost(Activity activity, String str) {
        if (StringUtils.isEmpty(str))
            return null;

        List<LinearLayout> list = new ArrayList<>();

        // 小费总是放在最后一个
        String[] lines = str.split("&");
        String[] contens;
        int lineLen = lines.length;

        if (lineLen < 1)
            return list;

        if (lines[lineLen - 1].length() < 3) {
            lineLen = lineLen - 1;
        }

        LinearLayout.LayoutParams container_params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        container_params.gravity = Gravity.CENTER_VERTICAL;
        LinearLayout.LayoutParams label_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        label_params.weight = 1;

        LinearLayout ll_container;
        TextView tv_desc, tv_content;

        int padding = DensityUtils.dip2px(activity, 3);


        for (int i = 0; i < lineLen; i++) {
            if (StringUtils.isEmpty(lines[i]))
                continue;

            contens = lines[i].split("\\|");
            if (contens.length < 2)
                continue;

            ll_container = new LinearLayout(activity);
            ll_container.setLayoutParams(container_params);
            ll_container.setOrientation(LinearLayout.HORIZONTAL);
            ll_container.setPadding(0, padding, 0, padding);

            tv_desc = new TextView(activity);
            tv_desc.setLayoutParams(label_params);
            tv_desc.setGravity(Gravity.LEFT);
            tv_desc.setTextSize(14);
            tv_desc.setTextColor(activity.getResources().getColor(R.color.label_white));

            tv_content = new TextView(activity);
            tv_content.setLayoutParams(label_params);
            tv_content.setGravity(Gravity.RIGHT);
            tv_content.setTextSize(14);
            tv_content.setTextColor(activity.getResources().getColor(R.color.label_white));

            tv_desc.setText(contens[0]);
            tv_content.setText(contens[1]);
            ll_container.addView(tv_desc);
            ll_container.addView(tv_content);

            list.add(ll_container);
        }

        return list;
    }

    /**
     * 计算夜间费时长,返回的是秒
     */
    public static long calcNightLength(String startTime, String endTime, long orderStartTime) {
        DateTime current = new DateTime(new Date());
        DateTime orderStart = new DateTime(new Date(orderStartTime));

        String[] startTimes = startTime.split(":");
        String[] endTimes = endTime.split(":");

        DateTime start = new DateTime(new Date());
        start.setHour(Integer.parseInt(startTimes[0]));
        start.setMinute(Integer.parseInt(startTimes[1]));

        DateTime end = new DateTime(new Date());
        end.setHour(Integer.parseInt(endTimes[0]));
        end.setMinute(Integer.parseInt(endTimes[1]));

        if (end.isBefore(start) && current.isBefore(end)) {
            start.addDay(-1);
        } else if (end.isBefore(start)) {
            end.addDay(1);
        }

        DateTime calcStartTime = null, calcEndTime = null;
        //确定起始计算时间(夜间费开始时间 、 订单开始时间  、没有开始)
        if (orderStart.isBefore(start) && start.isBefore(current)) {
            calcStartTime = start;
        } else if (start.isBefore(orderStart) && orderStart.isBefore(end)) {
            calcStartTime = orderStart;
        }

        if (calcStartTime == null)
            return 0;

        if (current.isBefore(end)) {
            calcEndTime = current;
        } else if (end.isBefore(current)) {
            calcEndTime = end;
        }

        long endMills = calcEndTime.getTimeInMillis();
        long startMills = calcStartTime.getTimeInMillis();

        return (endMills - startMills) / 1000;

    }


    /**
     * des解密(%2B为服务器自动转换的)
     *
     * @param str
     * @return
     */
    public static String DesDecrypt(String str) {
        str = str.replaceAll("%2B", "+");
        try {
            return CipherUtils.decryptDES(Base64.decode(str),
                    Constants.CONFIG_DES_KEY,
                    Constants.CONFIG_DES_IV);
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * des加密
     *
     * @param str
     * @return
     */
    public static String DesEncry(String str) {
        try {
            byte[] encryptDES = CipherUtils.encryptDES(str,
                    Constants.CONFIG_DES_KEY,
                    Constants.CONFIG_DES_IV);
            return Base64.encode(encryptDES);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取cmd命令的标志位位置
     *
     * @param cmd
     * @return
     */
    public static int[] getCmdFlagIndex(String cmd) {
        int length = cmd.length() / 2;
        String tmp;
        int fristIndex = -1, secondIndex = -1;
        for (int i = 0; i < length; i++) {
            tmp = cmd.substring(i * 2, i * 2 + 2).toUpperCase();
            if (Protocl.FLAG_CMD.equals(tmp)) {
                if (fristIndex < 0)
                    fristIndex = i * 2;
                else {
                    secondIndex = i * 2;
                    break;
                }
            }
        }
        int[] result = new int[2];
        result[0] = fristIndex;
        result[1] = secondIndex;
        return result;
    }

    /**
     * 保留小数点后几位
     *
     * @param numStr
     * @param n      小数点后几位
     * @return
     */
    public static double formatPoint(double numStr, int n) {
        BigDecimal temp = new BigDecimal(numStr);
        double num = temp.setScale(n, BigDecimal.ROUND_HALF_UP).doubleValue();

        return num;
    }

    /**
     * 保留小数点后几位
     *
     * @param numStr
     * @param n      小数点后几位
     * @return
     */
    public static float formatPoint(float numStr, int n) {
        BigDecimal temp = new BigDecimal(numStr);
        float num = temp.setScale(n, BigDecimal.ROUND_HALF_UP).floatValue();

        return num;
    }

    public static String checkPhone(String phone) {
        String desc = null;
        if (StringUtils.isEmpty(phone))
            desc = "手机号不能为空";
        return desc;
    }

    public static String checkPwd(String pwd) {
        String desc = null;
        if (StringUtils.isEmpty(pwd))
            desc = "密码不能为空";
        return desc;
    }

    public static void downFile(String url, String path, final DownListenre downListenre) {
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        path = path + File.separator + "temp.apk";
        file = new File(path);
        if (file.exists())
            file.delete();
        LogUtil.log(SplashInteractorImpl.class, "down app:" + path + "---" + url);
        FileDownloader.getImpl().create(url).setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        int process = (int) ((soFarBytes / (float) totalBytes) * 100);
                        if (downListenre != null)
                            downListenre.onProcess(process);
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        if (downListenre != null)
                            downListenre.onComplted(task.getPath());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        if (downListenre != null)
                            downListenre.onError(e);
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        LogUtil.log(SplashInteractorImpl.class, "down warn:");
                    }
                }).start();
    }

    public interface DownListenre {
        void onProcess(int process);

        void onError(Throwable e);

        void onComplted(String path);
    }
}
